package com.aijk.commons.jedis;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.JedisCluster;

import java.util.HashSet;
import java.util.Set;

/**
 * Redis缓存对象
 * Created by ChenDeWei on 2016/6/7.
 */
public class JedisCache {
    private static Logger log = LoggerFactory.getLogger(JedisCache.class);

    private Set<String> keySet = new HashSet<>();
    private final String name;
    @SuppressWarnings("unchecked")
    private final int expire;
    private final JedisCluster jedisCluster;

    /**
     * 构造函数
     *
     * @param name         缓存名称
     * @param expire       过期时间，未启用，预留参数
     * @param jedisCluster 缓存工具类
     */
    public JedisCache(String name, int expire, JedisCluster jedisCluster) {
        this.name = name;
        this.expire = expire;
        this.jedisCluster = jedisCluster;
    }

    public Object get(String key) {
        String keyf = this.getKey(key);
        return JSON.parse(jedisCluster.get(keyf));
    }

    public void put(Object key, Object value) {
        if (value == null)
            return;
        String keyf = this.getKey(String.valueOf(key));
        jedisCluster.set(keyf, JSON.toJSONString(value, SerializerFeature.WriteClassName));
        this.keySet.add(keyf);
    }

    public void clear() {
        String[] s = null;
        keySet.toArray(s);
        jedisCluster.del(s);
    }

    public void delete(String key) {
        String keyf = this.getKey(key);
        byte[] keyb = keyf.getBytes();
        this.keySet.add(keyf);
        jedisCluster.del(keyb);
    }

    private String getKey(String key) {
        return name + ":" + key;
    }

}
